<%@page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@page import="java.util.Set,java.util.Iterator,com.wubo.sec.model.Menu" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<%!
	private String getGradeStr(int grade){
		String str = "";
		for(int i=grade; i>1; i--){
			str += "\u00A0\u00A0\u00A0\u00A0|";
		}
		if(grade>1)str += "--";
		return str;
	}
	String menus = null;
	private String getMenuSelect(String menus, String code){
		if(code != null){
			int index = menus.indexOf(code);
			int postn = index + code.length() + 1;
			if(index != -1){
				return menus.substring(0, postn)+" selected"+menus.substring(postn, menus.length());
			}
		}
		return menus;
	}
	private String printMenus(Set<Menu> menus){
		StringBuilder sb = new StringBuilder();
		if(menus != null){
			for(Iterator<Menu> i=menus.iterator(); i.hasNext();){
				Menu m = i.next();
				sb.append("<option value='"+m.getCode()+"'>"+getGradeStr(m.getGrade())+m.getName()+"</option>\n");
				sb.append( printMenus(m.getSubMenus()) );
			}
		}
		return sb.toString();
	}
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>菜单管理</title>
<!--[if IE]>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
<![endif]-->
<!-- Main Stylesheet --> 
<link rel="stylesheet" href="<%=request.getContextPath()%>/css/style.css" type="text/css" />
<!-- Your Custom Stylesheet --> 
<link rel="stylesheet" href="<%=request.getContextPath()%>/css/custom.css" type="text/css" />
<link href="<%=request.getContextPath()%>/lib/thickbox/thickbox.css" rel="stylesheet" type="text/css" />
<link href="<%=request.getContextPath()%>/lib/jquery/jquery.autocomplete.css" type="text/css" rel="stylesheet"/>
<style type="text/css">
	#show_area input[type="text"]{
		font-family:宋体;黑体;幼圆;楷体_GB2312;仿宋_GB2312;Arial,Helvetica,sans-serif;
		border:0px;width:100%;
	}
	.noborder {border:0px none; overflow:auto;}
	#menu_list li input {
		vertical-align: middle;
	}
</style>
<%@include file="/include/header.jsp" %>
<script src="<%=request.getContextPath()%>/lib/jquery/jquery-1.4.2.min.js"></script>
<script src="<%=request.getContextPath()%>/js/administry.js"></script>
<script src="<%=request.getContextPath()%>/lib/validator/formValidator_min.js"></script>
<script src="<%=request.getContextPath()%>/lib/validator/formValidatorRegex.js"></script>
<script src="<%=request.getContextPath()%>/lib/jquery/jquery.form.js"></script>
<script src="<%=request.getContextPath()%>/lib/thickbox/thickbox.js"></script>
<script src="<%=request.getContextPath()%>/lib/jquery/jquery.autocomplete.pack.js"></script>
<script src="<%=request.getContextPath()%>/lib/jquery/jquery.json.js"></script>
<script src="<%=request.getContextPath()%>/lib/jquery/jquery.jstree.js"></script>
<script src="<%=request.getContextPath()%>/lib/jquery/jquery.tipTip.min.js"></script>
<script src="<%=request.getContextPath()%>/js/function.js"></script>
<script src="<%=request.getContextPath()%>/js/page/pageRender.js"></script>
<script type="text/javascript"><!--
	function showAddMenuForm(){
		getById("addMenu").reset();
		showBox("#TB_inline?height=380&width=580&inlineId=edit_container", "增加菜单");
	}
	function showMenuTree(){
		showBox("#TB_inline?height=400&width=500&inlineId=tree_container", "管理菜单树");
		
		$("#menu_list").jstree({
  			"plugins" : [ "themes", "html_data", "dnd"],
  			"themes" : {
  				"theme" : "classic",
  				"dots" : true,
  				"icons" : true
  			},
  			"html_data" : {
  				"ajax" : {
  					"url" : path+"/protected/system/listForAssignMenu.action?result=checkbox",
  					"cache" : false
  				}
  			},
  			"dnd" : {
  	            /*"drop_finish" : function (data){
  	            	var r = data.r;
  	            	var str = [];
  	            	for(var p in r){
  	            		str.push(p+":"+r[p]);
  	            	}
  	            	Alert(str.join(","));
  	            },*/
  	             "drag_check" : function (data){  
  	                 return {
  	                     after : true,
  	                     before : true,
  	                     inside : true
  	                 };
  	             },
  	             "drop_check" : function(data){
  	            	 return true;
  	             }
  	         }
  		}).bind("move_node.jstree", function (e, data) {
  			if(! getById("tree_auto_update").checked){
  				return;
  			}
  			var r = data.rslt.r[0];
  			var o = data.rslt.o[0];
  			var np = data.rslt.np;
  			var op = data.rslt.op;
  			
  			var rid = $(r).attr("id");
  			var oid = $(o).attr("id");
  			var r_index = r.nodeIndex;
  			var npid = $(np).attr("id");
  			var opid = $(op).attr("id");
  			
  			if(npid == 'menu_list'){
  				npid = null;
  			}
  			if(opid == 'menu_list'){
  				opid = null;
  			}
  			
  			Mask.show();
	  		jQuery.ajax({
	  			url:path+'/protected/system/updateTreeStructMenu.action',
	  			dataType:'json',
	  			data: {
	  				"id": oid,
	  				"targetCode": rid,
	  				"nodeIndex": r_index,
	  				"originParentCode": opid,
	  				"newParentCode": npid
	  			},
	  			success:function(json){
	  				Ajax.callback(json);
	  				if(!json.success){
	  					this.rollback(data.rlbk);
	  				}else{
	  					refreshMenuTree();
	  				}
	  			}
	  		});
		});

  		
  		//展开配置树
  		$("#tree_openAll").bind("click", function(){
  			$("#menu_list").jstree("open_all");
  		});
  		//收起配置树
  		$("#tree_closeAll").bind("click", function(){
  			$("#menu_list").jstree("close_all");
  		});
  		//刷新配置树
  		$("#tree_refresh").bind("click", function(){
  			refreshMenuTree();
  		});
  		//保存树结构
  		$("#tree_saveStruct").bind("click", function(){
	  		function Menu(code, name){
  				this.code = code;
  				this.name = name;
  				this.subMenus = null;
  				this.setSubMenus = function(subMenus){this.subMenus = subMenus;}
  			}
  			var getChildNode = function(pn){
  				var menus = null;
  				var nodes = $(pn).children("li");
  				if(nodes.length > 0){
  					menus = [];
	  				nodes.each(function(i){
	  					var node = nodes[i];
	  					var menu = new Menu( $(node).attr("id"), $(node).children("a").text() );
	  					var subEl = $(node).children("ul");
	  					if(subEl){
		  					menu.setSubMenus( getChildNode(subEl[0]) );
	  					}
	  					menus.push(menu);
	  				});
  				}
  				return menus;
  			}
  			var tree = $("#menu_list").jstree("get_container");
  			var data = tree.children();
  			if(data){
  				var root = data[0];
  				var list = getChildNode(root);
  				if( confirm("准备提交数据，是否继续？") ){
					Mask.show();
					jQuery.ajax({
			  			url:path+'/protected/system/saveTreeStructMenu.action',
			  			type:'post',
			  			dataType:'json',
			  			data: {"trees": $.JSON.encode(list)},
			  			success:function(json){
			  				Ajax.callback(json);
			  				refreshMenuTree();
			  			}
			  		});
	    		}
  			}
  			
  		});
  		//删除多个菜单
  		$("#tree_delete").bind("click", function(){
  			var menuCodes = document.getElementsByName("menuCode");
			var menuCode = [];
    		for(var i=0; i<menuCodes.length; i++){
    			if(menuCodes[i].checked){
    				menuCode.push(menuCodes[i].value);
    			}
    		}
    		if(menuCode.length < 1){showTip("请选择菜单！");return;}
    		if( confirm("是否删除所选菜单？") ){
				Mask.show();
				jQuery.ajax({
		  			url:path+'/protected/system/delsMenu.action',
		  			dataType:'json',
		  			data: {"id": menuCode.join(",")},
		  			success:function(json){
		  				Ajax.callback(json);
		  				refreshMenuTree();
		  			}
		  		});
    		}
  		});
	}
	function refreshMenuTree(){
		$("#menu_list").jstree("refresh", -1);
	}
	window.onload = init;
	function init(){
		pageBar = new PageRender({
			method: 'post',
			url:'<%=request.getContextPath()%>/protected/system/listMenu.action',
			start: <s:property value="start"/>,
			limit: <s:property value="limit"/>,
			total: <s:property value="total"/>,
			beforeLoad: function(){Mask.show();},
			data: {
				"menuname" : "#s_menuName",
				"orderby" : "#orderby",
				"locked" : "#locked",
				"leaf" : "#leaf",
				"active" : "#active"
			},
			renderTo: "page_bar"
		});
	}
	function doSearch(){
		pageBar.position(1);
	}
$(document).ready(function(){
	Administry.contextBoxInit();
	Administry.tipInit();
	
	<sec:authorize ifAnyGranted="ADMIN,MENU_ADD">
		$.formValidator.initConfig({
			formID:"addMenu",
			onError:function(msg){
				showTip(msg)
			},
			onSuccess:function(){
				if( confirm("准备提交数据，是否继续？") ){
					Mask.show();
					$('#addMenu').ajaxSubmit(Ajax.callback);
				}
				return false;
			}
		});
		$("#name").formValidator({
			ohShow:"请输入菜单名",
			onFocus:"2-50个字符"
		}).inputValidator({min:2,max:30});
		$("#orderIndex").formValidator({
			onShow:"菜单等级索引顺序，可为空",
			onFocus:"菜单等级从1开始，代表同级菜单中的顺序",
			empty:true
		}).inputValidator({type:'number',min:1,max:100});
	</sec:authorize>
		
	//AutoComplete菜单名关键字输入框
	$("#s_menuName").autocomplete(
	'<%=request.getContextPath()%>/protected/system/autoCompleteMenu.action',
	{
		width: 160,
		max: 10,
		scroll: true,
		scrollHeight: 300,
		dataType: 'json',
		matchCase:true,
		parse: function(data) {
			if(!isArray(data)){
				data = eval("("+data+")");
			}
			var rows = [];
			for(var i=0; i<data.length; i++){
				rows.push({
					"data" : data[i],
					"value" : data[i],
					"result" : this.formatResult && this.formatResult(data[i], data[i]) || data[i]
				});
			}
			return rows;
		},
		formatItem: function(data, i, total) {
			return data;
		}
	});
});
--></script>
</head>
<body>
	<%@include file="/include/body.jsp" %>
	
<s:if test="flag">
	<!-- 显示操作成功 -->
	<script type="text/javascript">
		showTip("操作成功");
	</script>
</s:if>

<!-- Wrapper -->
<div class="wrapper">
	 <s:if test="menuTree != null">
		<s:set value="menuTree" var="list"></s:set>
		<%
			menus = printMenus((Set) pageContext.getAttribute("list"));
		%>
	 </s:if>
	 <div class="content-box resizable" id="query_area">
    	<header>
			<h3>搜索</h3>
		</header>
		<section>
		<table class="no-style">
			<tbody>
			<tr>
				<td>
		        	<span>菜单名关键字:
		        		<input id="s_menuName" type="text" name="s_menuName" value="<s:property value="menuname"/>"/>
		        	</span>
		        	<span>锁定状态：
		        		<s:select id="locked" value="locked"  theme="simple" list="#{'2':'全部','0':'未锁定','1':'锁定'}">
				   		</s:select>
		        	</span>
		        	<span>叶子：
		        		<s:select id="leaf" value="leaf"  theme="simple" list="#{'2':'全部','1':'是','0':'否'}">
				   		</s:select>
		        	</span>
		        	<span>启用：
		        		<s:select id="active" value="active"  theme="simple" list="#{'2':'全部','1':'是','0':'否'}">
				   		</s:select>
		        	</span>
		            <span>
						<button class="btn" type="submit" onclick="doSearch();"><span class="icon icon-search"></span>搜 索</button>
					</span>
				</td>
			</tr>
			</tbody>
		</table>
		</section>
	</div>
	<div class="content-box" id="show_area">
	<header>
		<h3>
			<span>菜单列表</span>
	    	<span>排序：
	    	<s:select id="orderby" value="orderby" onchange="doSearch();" theme="simple" 
	   			list="#{' order by name asc':'菜单名',' order by grade asc, orderIndex asc':'等级和同级索引'}">
	   		</s:select>
    	</span>
		</h3>
		<div>
   		<span>
   			<a class="btn btn-gray" href="javascript:void(0)" onclick="doSearch();"><span class="icon icon-refresh"></span>刷新</a>
   		</span>
	 	<sec:authorize ifAnyGranted="ADMIN,MENU_ADD">
   		<span>
   			<a class="btn" href="javascript:void(0)" onclick="javascript:showAddMenuForm();"><span class="icon icon-add"></span>增加菜单..</a>
   		</span>
   		<span>
   			<a class="btn" href="javascript:void(0)" onclick="javascript:showMenuTree();">管理菜单树..</a>
   		</span>
	    </sec:authorize>
    	</div>
	</header>
	<section>
    <table class="display stylized" id="data_table">
    <thead>
		<tr>
			<th>序号</th><th>菜单名</th><th>URL</th><th>图标</th>
			<th>等级</th><th>同级索引</th><th>父菜单</th>
			<th>叶子</th><th>锁定</th><th>启用</th><th>权限过滤</th>
			<th>描述</th>
			<th>操作</th>
		</tr>
		</thead>
		<tbody>
		 	<s:if test="menus != null">
				<s:iterator value="menus" status="menustatus">
					<form id="form_<s:property value="code"/>" action="<s:url value='editMenu.action'></s:url>" method="post">
					<input type="hidden" name="menu.code" value="<s:property value="code"/>"/>
					<tr>
						<td><s:property value="#menustatus.index + 1 + start"/></td>
						<td><input type="text" name="menu.name" value="<s:property value="name"/>"/></td>
						<td><input type="text" name="menu.url" value="<s:property value="url"/>"/></td>
						<td><input type="text" name="menu.icon" size="3" value="<s:property value="icon"/>"/></td>
				 		<td><input type="text" name="menu.grade" value="<s:property value="grade"/>" size="2"/></td>
				 		<td><input type="text" name="menu.orderIndex" value="<s:property value="orderIndex"/>" size="2"/></td>
				 		<td>
				 			<s:set value="parentCode" var="parentCode" scope="page"/>
				 			<select name="menu.parentCode">
							<option value="">-- 请选择 --</option>
				 			<%
								out.print( getMenuSelect(menus, (String)pageContext.getAttribute("parentCode")) );
							%>
							</select>
				 		</td>
				 		<s:if test="#attr.SEC_ISADMIN || ! locked">
				 		<td><input type="checkbox" name="menu.leaf" value="true" <s:if test="leaf">checked</s:if>/></td>
				 		<td><input type="checkbox" name="menu.locked" value="true" <s:if test="locked">checked</s:if>/></td>
				 		</s:if>
				 		<s:else>
				 		<td>
				 			<input type="hidden" name="menu.leaf" value="<s:property value="leaf"/>" />
				 			<s:if test="leaf">是</s:if><s:else>否</s:else>
				 		</td>
				 		<td>
				 			<input type="hidden" name="menu.locked" value="<s:property value="locked"/>" />
				 			<s:if test="locked">已锁定</s:if><s:else>未锁定</s:else>
				 		</td>
				 		</s:else>
				 		<td><input type="checkbox" name="menu.active" value="true" <s:if test="active">checked</s:if>/></td>
				 		<td><input type="checkbox" name="menu.filter" value="true" <s:if test="filter">checked</s:if>/></td>
				 		<td><input type="text" name="menu.desn" value="<s:property value="desn"/>" /></td>
				 		<td style="white-space:nowrap">
				 			<s:if test="!locked || #attr.SEC_ISADMIN">
				 			<sec:authorize ifAnyGranted="ADMIN,MENU_UPDATE">
				 			<a href="javascript:void(0);" onclick="if(confirm('请确认')){Mask.show();$('#form_<s:property value="code"/>').ajaxSubmit(Ajax.callback);}">［更新］</a>
				 			</sec:authorize>
				 			</s:if>
				 			<s:if test="!locked">
				 			<sec:authorize ifAnyGranted="ADMIN,MENU_DELETE">
				 			<a href="javascript:void(0);" onclick="if(confirm('是否删除菜单?')){document.location.href='<s:url value="delMenu.action?id=%{code}"/>';}">［删除］</a>
				 			</sec:authorize>
				 			</s:if>
				 		</td>
				 	</tr>
				 	</form>
				</s:iterator>
			</s:if>
		 </tbody>
	</table>
	<div id="page_bar"></div>
	</section>
	</div>
</div>
<!-- 对话框 -->
<sec:authorize ifAnyGranted="ADMIN,MENU_ADD">
<div id="edit_container" style="display:none;" title="增加菜单">
	 <div id="add_menu_area_wrap">
	 	<s:form id="addMenu" action="addMenu" method="post" theme="simple">
			<table class="no-style">
				<tr>
					<td><label class="required">菜单名</label></td>
					<td><input type="text" id="name" name="menu.name" value=""/></td>
					<td><div id="nameTip"></div></td>
				</tr>
				<tr>
					<td><label class="required">URL</label></td>
					<td><input type="text" name="menu.url" value=""/></td>
					<td></td>
				</tr>
				<tr>
					<td><label>菜单图标</label></td>
					<td><input type="text" name="menu.icon" value=""/></td>
					<td></td>
				</tr>
				<tr>
					<td><label>同级索引</label></td>
					<td><input type="text" id="orderIndex" name="menu.orderIndex" value=""/></td>
					<td><div id="orderIndexTip"></div></td>
				</tr>
				<tr>
					<td><label>父菜单</label></td>
					<td>
						<select name="menu.parentCode">
						<option value="">-- 请选择 --</option>
						<%
							menus = printMenus((Set) pageContext.getAttribute("list"));
							out.print( getMenuSelect(menus, null) );
						%>
						</select>
					</td>
					<td></td>
				</tr>
				<tr>
					<td><label>叶子</label></td>
					<td><input type="checkbox" name="menu.leaf" value="true" checked/></td>
					<td></td>
				</tr>
				<s:if test="#attr.SEC_ISADMIN">
				<tr>
					<td><label>锁定状态</label></td>
					<td><input type="checkbox" name="menu.locked" value="true"/></td>
					<td></td>
				</tr>
				</s:if>
				<tr>
					<td><label>启用</label></td>
					<td><input type="checkbox" name="menu.active" value="true" checked/></td>
					<td></td>
				</tr>
				<tr>
					<td><label>权限过滤</label></td>
					<td><input type="checkbox" name="menu.filter" value="true"/></td>
					<td></td>
				</tr>
				<tr>
					<td><label>描述</label></td>
					<td><input type="text" name="menu.desn" value=""/></td>
					<td></td>
				</tr>
			</table>
			<div class="form-btn">
				<button class="btn btn-green" id="submitAddMenu" type="submit"><span class="icon icon-ok"></span>提 交</button>
				<button class="btn" type="reset" onclick="javascript:tb_remove();"><span class="icon icon-close"></span>取消</button>
			</div>
		 </s:form>
	</div>
</div>
</sec:authorize>
<div id="tree_container" style="display:none;" title="菜单树">
	<div id="sidetreecontrol" style="height:30px;">
		<div style="float:left;">
		<span><a id="tree_openAll" class="btn" href="javascript:void(0)">展开</a></span>
		<span><a id="tree_closeAll" class="btn" href="javascript:void(0)">收起</a></span>
		<span><a id="tree_refresh" class="btn" href="javascript:void(0)">刷新</a></span>
		</div>
		<div style="float:right;">
		<span style="margin:0 5px;">
			<a id="tree_saveStruct" class="btn" href="javascript:void(0);"><span class="icon icon-ok"></span>保存结构</a>
			<input type="checkbox" id="tree_auto_update" name="auto_update" value=""/>
			<span title="每当菜单结构变动都将自动保存" style="text-decoration:underline;">自动</span>
		</span>
		<span style="margin:0 5px;">
			<a id="tree_delete" class="btn" href="javascript:void(0);"><span class="icon icon-del"></span>删除</a>
			<span title="删除菜单，当删除父菜单时其子菜单自动上升一级" style="text-decoration:underline;">提示</span>
		</span>
		</div>
	</div>
	<div id="menu_list" style="height:90%;overflow:auto;clear:both;">
		
	</div>
</div>
</body>
</html>